'use strict';

const { Service } = require('egg');
const ModelName = 'Staff'
const dayjs = require("dayjs");
class RouterService extends Service {
  getTimeList(value) {
    let timeList = []
    // 如果是当天，从最近得半小时整开始，如果是明天，从0点开始
    if (value === dayjs().format('YYYY-MM-DD')) {
      // 每半小时一个时间段
      for (let i = 0; i < 48; i++) {
        let hour = Math.floor(i / 2)
        let minute = i % 2 === 0 ? '00' : '30'
        timeList.push({
            time: `${hour < 10 ? '0' + hour : hour}:${minute}`,
            status: 1,
            statusText: '可预约'
        })
      }
    } else {
      for (let i = 0; i < 48; i++) {
        let hour = Math.floor(i / 2)
        let minute = i % 2 === 0 ? '00' : '30'
        timeList.push({
          time: `${hour < 10 ? '0' + hour : hour}:${minute}`,
            status: 1,
            statusText: '可预约'
        })
      }
    }
    if (value === dayjs().format('YYYY-MM-DD')) {
      // 如果是今天 过滤timeList中小于现在的时间
      let hour = dayjs().hour()
      let minute = dayjs().minute()
      let nowTime = `${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`
      timeList = timeList.filter(timeItem => {
        let item = timeItem.time
        const startH = parseInt(item.split(':')[0])
        const startM = parseInt(item.split(':')[1])
        const nowH = parseInt(nowTime.split(':')[0])
        const nowM = parseInt(nowTime.split(':')[1])
        if (startH > nowH ) {
          if (startH === nowH + 1) {
            if (nowM > 30 && startM === 0) {
              return false
            } else {
              return  true
            }
          } else {
            if (startH > nowH) {
              return true
            } else {
              if (nowM < 30 && startM === 30) {
                return true
              }
              return false
            }
          }
        }
        return false
      })
    }
    return timeList
  }
  async serveTime(staff_id) {
    let dayList = [
      {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD'), children: []},
      {id: 1, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD'), children: []},
    ]
    for (let i = 0; i < dayList.length; i++) {
      const dayValue = dayList[i].value
      dayList[i].children = this.getTimeList(dayValue)
    }
    return dayList;
  }
  async login({ username, password }) {
    // 根据账号查询用户是否存在
    let user = await this.ctx.model[ModelName].findOne({
      where: { username, status: 1 },
    });
    if (!user) throw new Error('账号不存在');
    // 判断密码是否有误
    const isValid = user.password === password
    if (!isValid) {
      throw new Error('密码错误');
    }
    user = user.dataValues;
    delete user.password;
    return user;
  }

  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    console.log('----',where)
    return this.ctx.model[ModelName].findAndCountAll({
      where: {
        ...where,
      },
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','DESC']
      ],
    });
  }

  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where: {
        ...where,
      },
      order:[
        // id 降序
        ['create_time','ASC']
      ],
    });
  }
  async findOne(id) {
    // 今天已经接的订单
    const todayOrderCount = await this.ctx.model.Order.findAll({
        where: {
            staff_id: id,
            order_status: 0,
            pay_status: 1,
            status: 3
        }
    })
    const totalFinish = await this.ctx.model.Order.findAll({
      where: {
        staff_id: id,
        status: 4,
      }
    })
    const todayFinish = totalFinish.filter(item => {
      console.log('confirm_time',item.confirm_time)
      // confirm_time是当天的
        return dayjs(item.confirm_time).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD')
    })
    // 已完成
    const res = await this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
    });
    // 待审核的提现
    const withdrawList = await this.ctx.model.StaffBalance.findAll({
      where: {
        staff_id: id,
        status: -1
      }
    })
    // 计算总额
    let total = 0
    withdrawList.forEach(item => {
      total += parseFloat(item.amount)
    })

    if (!res) {
      throw new Error('未找到该用户')
      return
    }
    return {
        ...res.dataValues,
         balance: parseFloat(res.dataValues.balance) + total,
        todayOrder: todayOrderCount.length,
        todayFinish: todayFinish.length,
        totalFinish: totalFinish.length,
    }
  }

  /**
   * 创建
   * @param {*} data 角色信息
   */
  async create(data) {
    return this.ctx.model[ModelName].create(data);
  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    console.log('data', data)
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }

  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }
}

module.exports = RouterService;
